# -*- coding: utf-8 -*-

'''eof
name:申请企业存量业务保证类型校验
code:R61_EntInventoryBusinessGuaranteeTypeCheck
tableName:
columnName:
groups:业务其他规则校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import pandas as pd
import json
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')


def get_age(str1):
    try:
        date1 = datetime.now()
        date2 = date_format(str1)
        diff_year = date1.year - date2.year
        diff_month = date1.month - date2.month
        diff_day = date1.day - date2.day
        age = diff_year + diff_month / 12.0 + diff_day / 365.0
        return age
    except:
        return u'缺失值'


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def float_check(target):
    try:
        float(target)
        return True
    except:
        return False


def getRule61():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    vouchtypecodde_list = ["001001001001", "001001001002", "001001002001", "001001003001", "001003001001",
                           "001003001002",
                           "001003001003", "001004001001", "001004001002", "001004002001", "001004002002"]
    rejectList = [u'信用', u'企业保证', u'自然人保证', u'境外银行保证']
    rejectListTwo = ['010001', '010002', '010003']
    rejectListThree = ['10302030', '10302015', '10302020', '10302010']
    abnormalloan = json.loads(ratingRequest.get("abNormalloan"))
    # abnormalloan = ratingRequest.get("abNormalloan")
    resultList = []
    if abnormalloan not in null_type_list and isinstance(abnormalloan, list):
        if len(abnormalloan) >= 1:
            for i in abnormalloan:
                try:
                    vouchtype = i.get("vouchType")
                    customertype = i.get("customerType")
                    vouchtypecodde = i.get("vouchTypeCode")
                    businessType = i["businessType"]
                    contratctNo = i.get("contratctNo")
                    knowLendgeLoan = i.get("IsKnowLendgeLoan")
                except:
                    continue
                if customertype not in null_type_list:
                    if customertype == "1":
                        if knowLendgeLoan in ("1", 1):
                            resultList.append(1)
                            continue
                        if businessType in ("107010", "107055", "10101025"):
                            resultList.append(1)
                            continue
                        if vouchtype == u"信用":
                            if businessType in rejectListThree:
                                resultList.append(1)
                            else:
                                flag = True
                                for j in abnormalloan:
                                    customertype2 = j.get("customerType")
                                    contratctNo2 = j.get("contratctNo")
                                    businessType2 = j.get("businessType")
                                    if flag and customertype2 == "3" and customertype2 is not None and contratctNo == contratctNo2 and "10708C" == businessType2:
                                        flag = False
                                if flag:
                                    resultList.append(0)
                                else:
                                    resultList.append(1)
                        if vouchtype == u"保证":
                            resultList.append(0)
                        if vouchtype == u"抵押":
                            resultList.append(1)
                        if vouchtype not in null_type_list and vouchtypecodde not in null_type_list:
                            if vouchtype == u"质押" and vouchtypecodde in vouchtypecodde_list:
                                resultList.append(1)
                            elif vouchtype == u"质押":
                                resultList.append(0)
                            else:
                                resultList.append(1)
                        elif vouchtype in null_type_list and contratctNo not in null_type_list:
                            for j in abnormalloan:
                                customertype3 = j.get("customerType")
                                contratctNo3 = j.get("contratctNo")
                                businessType3 = j.get("businessType")
                                if customertype3 == "3" and contratctNo == contratctNo3 and businessType3 == "3010":
                                    resultList.append(1)
                        else:
                            resultList.append(2)
                else:
                    resultList.append(2)
            if 0 in resultList:
                return 0
            elif 1 in resultList or len(resultList) < 1:
                return 1
            else:
                raise ValueError("网贷传输的数据字段缺失或不符合要求")
        else:
            return 1
    else:
        raise RuntimeError("网贷传输的数据格式错误或者为空")


if __name__ == "__main__":
    ratingRequest = {"legalPersonIdCard": "500101199202192411", "timeLimit": "12",
                     "abNormalloan": [{"balance": "30", "businessType": u"个人业务", "customerType": "1"},
                                      {"balance": "30", "businessType": u"个业务", "customerType": "1", "contratctNo": "123123", "vouchType": u"信用"},
                                      {"balance": "30", "businessType": u"个业务", "customerType": "3", "contratctNo": "123123", "vouchType": u"信用"},
                                      {"balance": "30", "businessType": u"个业务", "customerType": "1"}]}
    aa = getRule61()
    print aa

result = getRule61()
